const mongoose = require('mongoose');

const canvasSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    collaborators: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }],
    img: {
        type: String,
        default: ''
    },
    zoom: {
        type: Number,
        default: 1
    },
    snapshot: {
        type: mongoose.Schema.Types.Mixed,
        default: null,
        validate: {
            validator: function(v) {
                // 允许任何有效的JSON对象
                return v === null || typeof v === 'object';
            },
            message: '快照必须是有效的JSON对象'
        }
    },
    shareCode: {
        code: String,
        expireAt: Date
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    updatedAt: {
        type: Date,
        default: Date.now
    }
});

// 更新时间中间件
canvasSchema.pre('save', function(next) {
    this.updatedAt = Date.now();
    next();
});

module.exports = mongoose.model('Canvas', canvasSchema);